<template>
    <div class="app-container">
        <!-- 文件上传区域 -->
        <el-upload ref="uploadRef" accept=".xls,.xlsx" action="/api/uploadTask" :on-remove="handleRemove"
            :on-error="handleError" :on-success="uploadSuccess" :disabled="importBtnDisabled" :file-list="fileList"
            :auto-upload="false" :limit="1" :headers="{ token: localStorage.getItem('token') }">
            <template #trigger>
                <el-button style="margin-left: 10px" size="small" type="primary">
                    从Excel导入<el-icon class="el-icon--right">
                        <Upload />
                    </el-icon>
                </el-button>
            </template>
            <el-button style="margin-left: 10px" size="small" type="success" :loading="loading" @click="submitUpload">
                上传到服务器<el-icon class="el-icon--right">
                    <UploadFilled />
                </el-icon>
            </el-button>

            <el-button class="add-button" size="small" type="primary" @click="downloadTemplate()">
                下载模板
                <el-icon class="el-icon--right">
                    <Download />
                </el-icon>
            </el-button>
            <template #tip>
                <div class="el-upload__tip" style="height: 30px">
                    只能上传xls/xlsx文件,导入新任务后将清空原来的任务,请一次性将本学期课程导入完毕
                </div>
            </template>
        </el-upload>

        <!-- 搜索和操作区域 -->
        <el-form :inline="true" :model="searchForm" class="demo-form-inline" style="margin-top: 20px;">
            <el-form-item label="班级编号">
                <el-input v-model="searchForm.classNo" placeholder="请输入班级编号"></el-input>
            </el-form-item>
            <el-form-item label="课程">
                <el-select v-model="searchForm.courseId" placeholder="请选择课程" clearable style="width: 180px">
                    <el-option 
                        v-for="course in courseList" 
                        :key="course.id" 
                        :label="course.courseName" 
                        :value="course.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="教师">
                <el-select v-model="searchForm.teacherId" placeholder="请选择教师" clearable style="width: 180px">
                    <el-option 
                        v-for="teacher in teacherList" 
                        :key="teacher.id" 
                        :label="teacher.teacherName" 
                        :value="teacher.id"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">查询 <el-icon class="el-icon--right"><Search /></el-icon></el-button>
                <el-button type="success" @click="handleAdd">新增任务 <el-icon class="el-icon--right"><Plus /></el-icon></el-button>
                <el-button type="danger" @click="handleBatchDelete" :disabled="multipleSelection.length === 0">批量删除 <el-icon class="el-icon--right"><Delete /></el-icon></el-button>
            </el-form-item>
        </el-form>

        <!-- 任务列表 -->
        <el-table 
            v-loading="listLoading" 
            :data="filteredList" 
            element-loading-text="Loading" 
            border 
            fit 
            highlight-current-row
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column align="center" label="序号" width="80px">
                <template #default="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="班级编号" prop="classNo" align="center">
                <template #default="scope">
                    {{ scope.row.classNo }}
                </template>
            </el-table-column>
            <el-table-column label="班级名" prop="className" align="center">
                <template #default="scope">
                    <span>{{ scope.row.className }}</span>
                </template>
            </el-table-column>
            <el-table-column label="教师编号" prop="teacherNo" align="center">
                <template #default="scope">
                    {{ scope.row.teacherNo }}
                </template>
            </el-table-column>
            <el-table-column label="教师姓名" prop="teacherName" align="center">
                <template #default="scope">
                    <span>{{ scope.row.teacherName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="课程编号" prop="courseNo" align="center">
                <template #default="scope">
                    {{ scope.row.courseNo }}
                </template>
            </el-table-column>
            <el-table-column label="课程名" prop="courseName" align="center">
                <template #default="scope">
                    <span>{{ scope.row.courseName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="课程属性" prop="courseAttr" align="center">
                <template #default="scope">
                    {{ scope.row.courseAttr }}
                </template>
            </el-table-column>
            <el-table-column label="总周数" prop="weeksSum" align="center">
                <template #default="scope">
                    {{ scope.row.weeksSum }}
                </template>
            </el-table-column>
            <el-table-column label="周学时" prop="weeksNumber" align="center">
                <template #default="scope">
                    {{ scope.row.weeksNumber }}
                </template>
            </el-table-column>
            <el-table-column label="开始周" prop="startWeek" align="center">
                <template #default="scope">
                    {{ scope.row.startWeek }}
                </template>
            </el-table-column>
            <el-table-column label="结束周" prop="endWeek" align="center">
                <template #default="scope">
                    {{ scope.row.endWeek }}
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200px">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑 <el-icon class="el-icon--right"><Edit /></el-icon></el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除 <el-icon class="el-icon--right"><Delete /></el-icon></el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增/编辑任务对话框 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60%">
            <el-form :model="taskForm" :rules="rules" ref="formRef" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="班级编号" prop="classNo">
                            <el-input v-model="taskForm.classNo" placeholder="请输入班级编号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="班级名" prop="className">
                            <el-input v-model="taskForm.className" placeholder="请输入班级名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="教师编号" prop="teacherNo">
                            <el-input v-model="taskForm.teacherNo" placeholder="请输入教师编号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="教师姓名" prop="teacherName">
                            <el-input v-model="taskForm.teacherName" placeholder="请输入教师姓名"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="课程编号" prop="courseNo">
                            <el-input v-model="taskForm.courseNo" placeholder="请输入课程编号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="课程名" prop="courseName">
                            <el-input v-model="taskForm.courseName" placeholder="请输入课程名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="课程属性" prop="courseAttr">
                            <el-input v-model="taskForm.courseAttr" placeholder="请输入课程属性"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="总周数" prop="weeksSum">
                            <el-input-number v-model="taskForm.weeksSum" :min="1" :max="20" style="width: 100%"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="周学时" prop="weeksNumber">
                            <el-input-number v-model="taskForm.weeksNumber" :min="1" :max="20" style="width: 100%"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开始周" prop="startWeek">
                            <el-input-number v-model="taskForm.startWeek" :min="1" :max="20" style="width: 100%"></el-input-number>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="结束周" prop="endWeek">
                            <el-input-number v-model="taskForm.endWeek" :min="1" :max="20" style="width: 100%"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Plus, Edit, Delete, Upload, UploadFilled, Download } from '@element-plus/icons-vue';
import axios from 'axios';

const list = ref([]);
const listLoading = ref(true);
const submitLoading = ref(false);
const multipleSelection = ref([]);

// 下拉选项数据
const courseList = ref([]);
const teacherList = ref([]);
const classList = ref([]);
const semesterList = ref([]);

const searchForm = ref({
    classNo: '',
    courseId: null,
    teacherId: null,
});

const dialogVisible = ref(false);
const dialogTitle = ref('');
const isEdit = ref(false);
const formRef = ref(null);

// 上传相关变量
const fileList = ref([]);
const loading = ref(false);
const importBtnDisabled = ref(false);
const uploadRef = ref(null);

const taskForm = ref({
    id: null,
    classNo: '',
    className: '',
    teacherNo: '',
    teacherName: '',
    courseNo: '',
    courseName: '',
    courseAttr: '',
    weeksSum: 16,
    weeksNumber: 2,
    startWeek: 1,
    endWeek: 16,
});

const rules = {
    classNo: [
        { required: true, message: '请输入班级编号', trigger: 'blur' },
        { min: 1, max: 20, message: '班级编号长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    className: [
        { required: true, message: '请输入班级名称', trigger: 'blur' },
        { min: 1, max: 50, message: '班级名称长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    teacherNo: [
        { required: true, message: '请输入教师编号', trigger: 'blur' },
        { min: 1, max: 20, message: '教师编号长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    teacherName: [
        { required: true, message: '请输入教师姓名', trigger: 'blur' },
        { min: 1, max: 50, message: '教师姓名长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    courseNo: [
        { required: true, message: '请输入课程编号', trigger: 'blur' },
        { min: 1, max: 20, message: '课程编号长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    courseName: [
        { required: true, message: '请输入课程名称', trigger: 'blur' },
        { min: 1, max: 50, message: '课程名称长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    weeksNumber: [
        { required: true, message: '请输入周学时', trigger: 'blur' },
        { type: 'number', min: 1, max: 20, message: '周学时必须在 1 到 20 之间', trigger: 'blur' }
    ],
    weeksSum: [
        { required: true, message: '请输入总周数', trigger: 'blur' },
        { type: 'number', min: 1, max: 20, message: '总周数必须在 1 到 20 之间', trigger: 'blur' }
    ]
};

const filteredList = computed(() => {
    if (!list.value) return [];
    return list.value.filter(item => {
        const classMatch = searchForm.value.classNo ? item.classNo.includes(searchForm.value.classNo) : true;
        const courseMatch = searchForm.value.courseId ? item.courseId === searchForm.value.courseId : true;
        const teacherMatch = searchForm.value.teacherId ? item.teacherId === searchForm.value.teacherId : true;
        return classMatch && courseMatch && teacherMatch;
    });
});

const getStatusText = (status) => {
    const statusMap = {
        '0': '未开始',
        '1': '进行中',
        '2': '已完成'
    };
    return statusMap[status] || '未知';
};

const getStatusTagType = (status) => {
    const tagTypeMap = {
        '0': 'info',
        '1': 'warning',
        '2': 'success'
    };
    return tagTypeMap[status] || '';
};

// 获取基础数据
const getBaseData = async () => {
    try {
        const headers = { "token": localStorage.getItem("token") };
        
        // 并行获取所有基础数据
        const [courseRes, teacherRes, classRes, semesterRes] = await Promise.all([
            axios.get('/api/course/getList', { headers }),
            axios.get('/api/teacher/getList', { headers }),
            axios.get('/api/classes/getList', { headers }),
            axios.get('/api/semester/getList', { headers })
        ]);
        
        courseList.value = courseRes.data.data || [];
        teacherList.value = teacherRes.data.data || [];
        classList.value = classRes.data.data || [];
        semesterList.value = semesterRes.data.data || [];
    } catch (error) {
        console.error('Failed to fetch base data:', error);
        ElMessage.error('获取基础数据失败');
    }
};

const getList = async () => {
    listLoading.value = true;
    try {
        const response = await axios.get('/api/task/getList', {
            headers: {
                "token": localStorage.getItem("token"),
            },
        });
        list.value = response.data.data || [];
        if (list.value.length === 0) {
            ElMessage.success("暂无任务信息");
        }
    } catch (error) {
        console.error('Failed to fetch list:', error);
        ElMessage.error('获取任务列表失败');
    } finally {
        listLoading.value = false;
    }
};

const handleSearch = () => {
    // 前端过滤，如果需要后端搜索可以调用 getList()
};

const handleAdd = () => {
    isEdit.value = false;
    dialogTitle.value = '新增任务';
    taskForm.value = {
        id: null,
        classNo: '',
        className: '',
        teacherNo: '',
        teacherName: '',
        courseNo: '',
        courseName: '',
        courseAttr: '',
        weeksSum: 16,
        weeksNumber: 2,
        startWeek: 1,
        endWeek: 16,
    };
    dialogVisible.value = true;
    // 重置表单验证
    if (formRef.value) {
        formRef.value.clearValidate();
    }
};

const handleEdit = (row) => {
    isEdit.value = true;
    dialogTitle.value = '编辑任务';
    taskForm.value = { ...row };
    dialogVisible.value = true;
    // 重置表单验证
    if (formRef.value) {
        formRef.value.clearValidate();
    }
};

const submitForm = async () => {
    if (!formRef.value) return;
    
    try {
        await formRef.value.validate();
        submitLoading.value = true;
        
        if (isEdit.value) {
            await axios.put(`/api/task/update/${taskForm.value.id}`, taskForm.value, {
                headers: {
                    "token": localStorage.getItem("token"),
                },
            });
            ElMessage.success('更新成功');
        } else {
            await axios.post('/api/task/add', taskForm.value, {
                headers: {
                    "token": localStorage.getItem("token"),
                },
            });
            ElMessage.success('新增成功');
        }
        dialogVisible.value = false;
        await getList();
    } catch (error) {
        if (error.message) {
            // 表单验证错误
            return;
        }
        console.error('Form submission error:', error);
        ElMessage.error(isEdit.value ? '更新失败' : '新增失败');
    } finally {
        submitLoading.value = false;
    }
};

const handleDelete = (row) => {
    ElMessageBox.confirm(`确定删除任务 ${row.taskName} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        try {
            await axios.delete(`/api/task/delete/${row.id}`, {
                headers: {
                    "token": localStorage.getItem("token"),
                },
            });
            ElMessage.success('删除成功');
            await getList();
        } catch (error) {
            console.error('Delete error:', error);
            ElMessage.error('删除失败');
        }
    }).catch(() => {
        // 用户取消操作
    });
};

const handleSelectionChange = (selection) => {
    multipleSelection.value = selection;
};

const handleBatchDelete = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要删除的任务');
        return;
    }
    
    const taskNames = multipleSelection.value.map(item => item.taskName).join('、');
    ElMessageBox.confirm(`确定删除选中的任务：${taskNames} 吗?`, '批量删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        try {
            const ids = multipleSelection.value.map(item => item.id);
            await axios.delete('/api/task/deleteBatch', {
                data: ids,
                headers: {
                    "token": localStorage.getItem("token"),
                },
            });
            ElMessage.success('批量删除成功');
            await getList();
            multipleSelection.value = [];
        } catch (error) {
            console.error('Batch delete error:', error);
            ElMessage.error('批量删除失败');
        }
    }).catch(() => {
        // 用户取消操作
    });
};

// 上传功能相关方法
const handleRemove = (file, fileList) => {
    console.log('文件移除:', file, fileList);
};

const handleUploadError = (err, file, fileList) => {
    console.error('上传失败:', err);
    ElMessage.error('文件上传失败');
    loading.value = false;
    importBtnDisabled.value = false;
};

const handleUploadSuccess = (response, file, fileList) => {
    console.log('上传成功:', response);
    if (response.code === 200) {
        ElMessage.success('文件上传成功');
        // 更新列表数据
        if (response.data && Array.isArray(response.data)) {
            list.value = response.data;
        }
    } else {
        ElMessage.error(response.message || '上传失败');
    }
    loading.value = false;
    importBtnDisabled.value = false;
};

const submitUpload = () => {
    if (fileList.value.length === 0) {
        ElMessage.warning('请先选择文件');
        return;
    }
    loading.value = true;
    importBtnDisabled.value = true;
    uploadRef.value.submit();
};

const downloadTemplate = () => {
    const link = document.createElement('a');
    link.href = '/api/task/downloadTemplate';
    link.download = '任务导入模板.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
};

onMounted(async () => {
    await getBaseData();
    await getList();
});

</script>

<style scoped>
.app-container {
    padding: 20px;
}
.demo-form-inline .el-input {
    width: 180px;
}
.dialog-footer {
    text-align: right;
}
</style>